package gu.sql2java.c3p0;

import static gu.sql2java.SimpleLog.log;

import javax.sql.DataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.mchange.v2.c3p0.DataSources;

import gu.sql2java.DataSourceConfig;
import gu.sql2java.DataSourceFactory;
import gu.sql2java.Constant.JdbcProperty;

/**
 * 基于c3p0实现{@link DataSourceFactory}接口
 * @author guyadong
 *
 */
public class C3p0DataSourceFactory implements DataSourceFactory{

	public C3p0DataSourceFactory() {
	}
	
    @Override
	public DataSource createDataSource(DataSourceConfig config){
		try{
			config.logDatabaseProperties();
			//set C3P0 properties
			ComboPooledDataSource ds = new ComboPooledDataSource();
			ds.setDriverClass(config.getJdbcDriver());
			ds.setUser(config.getJdbcUsername());
			ds.setPassword(config.getJdbcPassword());
			ds.setJdbcUrl(config.getJdbcUrl());
			ds.setMaxPoolSize(Integer.parseInt(config.getInitProperty(JdbcProperty.C3P0_MAXPOOLSIZE.key,"100")));
			ds.setMinPoolSize(Integer.parseInt(config.getInitProperty(JdbcProperty.C3P0_MINPOOLSIZE.key,"10")));
			ds.setMaxIdleTime(Integer.parseInt(config.getInitProperty(JdbcProperty.C3P0_MAXIDLETIME.key,"120")));
			ds.setIdleConnectionTestPeriod(Integer.parseInt(config.getInitProperty(JdbcProperty.C3P0_IDLECONNECTIONTESTPERIOD.key,"120")));
			return ds; 
		}catch (Exception e){
			throw new IllegalArgumentException(String.format("can't get connection by argument...driver/url/username/password[%s/%s/%s/%s]",
					config.getJdbcDriver(),config.getJdbcUrl(),config.getJdbcUsername(),config.getJdbcPassword()),e);
		}
	}
	@Override
	public void destroy(DataSource dataSource){
        try{
            DataSources.destroy(dataSource);
        }catch (Exception e) {
            log("dispose pool wrong ..." + e);
        }
	}
}
